package top.yuki.command;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryView;
import org.bukkit.inventory.ItemStack;
import top.yuki.Chat.ChatCharacteristic;
import top.yuki.Inventory.Package;
import top.yuki.LevelWorld;
import top.yuki.board.PlayerBoard;
import top.yuki.data.DataManager;
import top.yuki.goods.Prize;
import top.yuki.data.WorldManage;

import java.io.File;
import java.util.List;
import java.util.Objects;
import java.util.UUID;


public class CommandHandler implements CommandExecutor {
    String worldName;
    int level;
    UUID uid;
    LevelWorld lw = LevelWorld.instance;
    WorldManage worldManage = LevelWorld.worldManage;
    DataManager dataManage = LevelWorld.dataManage;
    Configuration config = lw.getConfig();

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (args.length == 0) {
            if (sender.isOp() || sender.hasPermission("levelworld.admin)")) {
                opShowHelp(sender);
            } else {
                showHelp(sender);
            }
            return true;
        } else {
            if (Objects.equals(args[0], "p")) {
                if (sender.hasPermission("levelworld.openPackage")) {
                    if (args.length == 1) {
                        sender.sendMessage("请输入要打开的世界");
                    }
                    openPackage(sender, args);
                }
                return true;
            }
            if (!sender.hasPermission("levelworld.admin")) {
                return false;
            }
            if (Objects.equals(args[0], "showTyep")) {
                Player player = (Player) sender;
                ItemStack itemInMainHand = player.getInventory().getItemInMainHand();
                Material type = itemInMainHand.getType();
                sender.sendMessage(type.toString());
                return true;

            } else if (Objects.equals(args[0], "setWorldLevel")) {
                if (setWorldLevel(sender, args)) {
                    return true;
                } else {
                    return false;
                }

            } else if (Objects.equals(args[0], "setLevel")) {
                setLevel(sender, args);
                sender.sendMessage("设置成功");
                return true;
            } else if (Objects.equals(args[0], "setPrize")) {

                Player p = (Player) sender;
                Prize prize = new Prize();
                prize.setPrize(p, args[1]);
                sender.sendMessage("设置成功");
                return true;
            } else if (Objects.equals(args[0], "dropPrize")) {
                dropPrize(sender, args);
                return true;
            } else if (Objects.equals(args[0], "spendEssence")) {
                spendEssence(sender, args);
                return true;
            } else if (Objects.equals(args[0], "addEssence")) {
                addEssence(sender, args);
                return true;
            } else if (Objects.equals(args[0], "sell")) {
                sell(sender);
                return true;

            } else if (Objects.equals(args[0], "reload")) {
                lw.reloadConfig();
                sender.sendMessage("重载配置文件成功");
            } else if (Objects.equals(args[0], "show")) {
                for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
                    int essence = dataManage.getEssence(onlinePlayer.getUniqueId());
                    int level = dataManage.getLevel(onlinePlayer.getUniqueId());
                    int worldLevel = dataManage.getWorldLevel(onlinePlayer.getUniqueId());
                    String name = onlinePlayer.getName();
                    sender.sendMessage(name + " 体力值:" + essence + "  等级:" + level + " 世界等级:" + worldLevel);
                }
                return true;

            }
        }


        return false;
    }


    private void spendEssence(CommandSender sender, String[] args) {
        Player p = Bukkit.getPlayer(args[1]);
        int essence = dataManage.getEssence(p.getUniqueId());
        int spendEssence = Integer.parseInt(args[2]);
        int perEssenceXp = (int) config.get("perEssenceXp");
        if (essence >= spendEssence) {
            dataManage.addXp(p.getUniqueId(), perEssenceXp * spendEssence);
            if (args[3] != null) {
                String commandName = args[3];
                String command = (String) config.get("command." + commandName);
                command = command.replace("{player}", p.getName());
                ConsoleCommandSender consoleSender = Bukkit.getConsoleSender();
                Bukkit.dispatchCommand(consoleSender, command);
            }
            p.sendMessage(ChatCharacteristic.SYSTEM_CAT.system + "奖励已发放，请查看背包");
        } else {
            p.sendMessage(ChatCharacteristic.SYSTEM_CAT.system + "精华不足");
        }
        PlayerBoard.refresh(p);
    }

    private void dropPrize(CommandSender sender, String[] args) {
        Player p = Bukkit.getPlayer(args[1]);
        Prize.dropPrize(p, args[2]);
    }

    private void addEssence(CommandSender sender, String[] args) {
        if (args.length == 2) {
            Player p = (Player) sender;
            int addNum = Integer.parseInt(args[1]);
            dataManage.addEssence(p.getUniqueId(), addNum);
            PlayerBoard.refresh(p);
        } else if (args.length == 3) {
            Player p = Bukkit.getPlayer(args[1]);
            int addNum = Integer.parseInt(args[2]);
            dataManage.addEssence(p.getUniqueId(), addNum);
            PlayerBoard.refresh(p);
            p.sendMessage(ChatCharacteristic.SYSTEM_CAT.system + "已恢复精华");
        }
    }

    private void openPackage(CommandSender sender, String[] args) {
        Player player = (Player) sender;
        int targetWorldLevel = Integer.parseInt(args[1]);
        int playerLocalWorldLevel = worldManage.getWorldLevel(player.getWorld().getName());
        if (targetWorldLevel > playerLocalWorldLevel) {
            sender.sendMessage(ChatCharacteristic.SYSTEM_CAT.system + "无法获取上层世界的物品");
            return;
        } else if (targetWorldLevel == 0) {
            sender.sendMessage(ChatCharacteristic.SYSTEM_CAT.system + "无法获得0级世界的物品");
            return;
        } else if (targetWorldLevel == playerLocalWorldLevel) {
            sender.sendMessage(ChatCharacteristic.SYSTEM_CAT.system + "无法获取本级世界的物品");
            return;
        }
        File f = new File(lw.getDataFolder() + File.separator + "worldData" + File.separator + targetWorldLevel + File.separator + player.getName() + ".yml");
        if (f.exists()) {
            ItemStack[] itemStacks = Package.openPackage(targetWorldLevel, player);
            Inventory inventory = Bukkit.createInventory(player, 45, targetWorldLevel + "级世界背包");
            inventory.setContents(itemStacks);
            player.openInventory(inventory);
        } else {
            player.sendMessage(ChatCharacteristic.SYSTEM_CAT.system + "世界" + targetWorldLevel + "无文件");
        }

    }

    private void sell(CommandSender sender) {
        Player player = (Player) sender;


    }

    private void showWorld(CommandSender sender) {
        List<World> worlds = Bukkit.getWorlds();
        for (World world : worlds) {
            sender.sendMessage(world + "   " + worldManage.getWorldLevel(world.getName()));

        }
    }

    private boolean setLevel(CommandSender sender, String[] args) {

        if (args.length == 3) {
            Player player = Bukkit.getPlayer(args[1]);
            int level = Integer.parseInt(args[2]);
            dataManage.setLevel(player.getUniqueId(), level);
            PlayerBoard.refresh(player);
            return true;
        } else if (args.length == 2) {
            Player player = (Player) sender;
            int level = Integer.parseInt(args[1]);
            dataManage.setLevel(player.getUniqueId(), level);
            PlayerBoard.refresh(player);
            return true;
        }

        return false;
    }

    private boolean setWorldLevel(CommandSender sender, String[] args) {
        if (args.length == 2) {
            if (sender instanceof Player) {
                Player player = (Player) sender;
                worldName = player.getWorld().getName();
                level = Integer.parseInt(args[1]);
                uid = player.getWorld().getUID();
            } else {
                sender.sendMessage("无世界参数仅能在玩家状态使用");
                return true;
            }
        } else if (args.length == 3) {
            worldName = args[1];
            level = Integer.parseInt(args[2]);
            uid = Bukkit.getWorld(worldName).getUID();
        }
        boolean b = worldManage.setWorld(uid, worldName, level);
        if (b) {
            sender.sendMessage(worldName + "设置为等级" + level);
            return true;
        }
        return false;
    }

    public void opShowHelp(CommandSender sender) {
        sender.sendMessage("/lw addExclude   将手中物品添加到传送排除列表");
        sender.sendMessage("/lw setWorldLevel [world] {level}");
        sender.sendMessage("/lw setLevel [player] {level}");
        sender.sendMessage("/lw setPrize {name}  将背包物品设置为奖品(设置为均值，掉落根据正态分布随机数量)");
        sender.sendMessage(("/lw dropPrize {player} {name} 给某人发放奖品,需要精华值"));
        sender.sendMessage(("/lw spendEssence {player} {Essence} [commandName] 扣除某人精华并发放经验，成功则执行配置文件的命令"));
        sender.sendMessage(("/lw addEssence [Player] {number}  添加某人精华值"));
        sender.sendMessage(("/lw show   显示所有人数据"));
        sender.sendMessage("/lw p {世界等级}   打开某个世界的背包，注意只能单向获取");
        sender.sendMessage("/lw sell 出售物品");
        sender.sendMessage("/lw reload");
    }

    public void showHelp(CommandSender sender) {
        sender.sendMessage("/lw p {worldLevel}   打开某个世界的背包");
    }
}
